@echo off
echo.
echo 🚀 LongImageReader MSVC 构建脚本
echo =====================================

:: Set colors
set "GREEN=[92m"
set "RED=[91m"
set "YELLOW=[93m"
set "BLUE=[94m"
set "NC=[0m"

:: Check for Visual Studio
call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1
if errorlevel 1 (
    echo %RED%❌ Visual Studio 2022 not found%NC%
    echo Please install Visual Studio 2022 with C++ development tools
    pause
    exit /b 1
)

echo %GREEN%✅ Visual Studio 2022 environment loaded%NC%

:: Check for Qt MSVC installation
set "QT_MSVC_ROOT=C:\Qt\6.9.2\msvc2019_64"
if not exist "%QT_MSVC_ROOT%" (
    echo %YELLOW%⚠️  Qt MSVC version not found at %QT_MSVC_ROOT%%NC%
    echo Trying to use existing Qt installation...
    set "QT_MSVC_ROOT=C:\Qt\6.9.2\mingw_64"
)

if not exist "%QT_MSVC_ROOT%" (
    echo %RED%❌ Qt installation not found%NC%
    pause
    exit /b 1
)

echo %GREEN%✅ Using Qt at: %QT_MSVC_ROOT%%NC%

:: Clean build directory
echo.
echo %BLUE%🧹 清理构建目录...%NC%
if exist "build_msvc" rmdir /s /q "build_msvc"

echo %BLUE%📁 创建构建目录...%NC%
mkdir "build_msvc"
cd "build_msvc"

:: Configure with CMake for MSVC
echo.
echo %BLUE%⚙️ 配置 CMake 项目 (MSVC)...%NC%
cmake -G "Visual Studio 17 2022" -A x64 -DCMAKE_PREFIX_PATH="%QT_MSVC_ROOT%" -DUSE_POPPLER=ON ..
if errorlevel 1 (
    echo %RED%❌ CMake 配置失败%NC%
    pause
    exit /b 1
)

echo %GREEN%✅ CMake 配置成功%NC%

:: Build with MSBuild
echo.
echo %BLUE%🔨 开始编译项目 (MSVC Release)...%NC%
cmake --build . --config Release --parallel
if errorlevel 1 (
    echo %RED%❌ 编译失败%NC%
    pause
    exit /b 1
)

echo %GREEN%✅ 编译成功%NC%

:: Copy executable to main directory for easy access
copy "Release\LongImageReader.exe" "..\LongImageReader_msvc.exe" >nul 2>&1

echo.
echo %GREEN%🎉 构建完成！%NC%
echo %GREEN%📍 可执行文件位置: LongImageReader_msvc.exe%NC%
echo.
pause